import dynamic from 'next/dynamic'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import cm from 'classnames'
import { getPublishSource } from '@/api/score'
import { useRouter } from 'next/router'

const ModalPoster = dynamic(() => import('@c/modal/modal-poster-share'))

const Index = () => {
  const { query } = useRouter()
  const [showPoster, togglePoster] = useState(false)
  const [times, setTimes] = useState(0)
  const [code, setCode] = useState(query.invite_code ? query.invite_code : '')
  const handleInvite = () => {
    // 有code,直接打开弹窗,TV侧打开海报
    if (query.invite_code) {
      togglePoster(true)
      return
    }
    // 手机测有id,直接使用原生分享
    try {
      const isTest = process.env.NEXT_PUBLIC_BAN_CONSOLE != '1'
      const url = `https://${isTest ? 'web' : 'www'}.histar.tv/invited`
      window.android.share(url)
    } catch (error) {
      // 不在手机则直接打开
      togglePoster(true)
    }
  }

  const getMyScore = async () => {
    if (!localStorage.getItem('token')) {
      return
    }
    const res = await getPublishSource()
    setTimes(res?.data?.inviteTimes || 0)
  }

  useEffect(() => {
    getMyScore()
    try {
      const userInfo = window.android.getUserInfo()
      const userObj = JSON.parse(userInfo)
      setCode(userObj.user.id)
    } catch (error) {}
  }, [])

  return (
    <div className={styles.landMain}>
      <div className={styles.landHead}>
        <img src="/images/pc-land-head.webp" alt="邀请步骤" className={cm('w-full', 'hideWhenPhone')} />
        {!!times && (
          <div className={cm(styles.static, 'hideWhenPhone')}>
            您已经成功邀请<span>{times}</span>位好友
          </div>
        )}
      </div>
      <div className={cm(styles.landBody, 'hideWhenPc')}>
        <img src="/images/active-step-h5.webp" alt="邀请步骤" className={cm(styles.bodyImg, styles.bodyImgPhone)} />
        <p className={styles.tips}>小tips：分享到群聊效果更好哦~</p>
        <div className={styles.invite}>
          您已经成功邀请<span>{times}</span>位好友！
        </div>
      </div>
      <img alt="邀请好友" src="/images/invite-user-btn.webp" className={styles.inviteBtn} onClick={handleInvite} />
      {showPoster && <ModalPoster code={code} onClose={() => togglePoster(false)} />}
    </div>
  )
}
export default Index

export async function getServerSideProps() {
  return {
    props: {
      layoutProps: {
        noSomeMetaInfo: false,
        title: '邀请好友解锁星视界！',
        desc: '邀请好友解锁星视界！'
      }
    }
  }
}
